import { invoke } from '@tauri-apps/api/core'
import type { 
  Device, CreateDeviceRequest,
  SocialAccount, CreateAccountRequest,
  Task, CreateTaskRequest, TaskLog,
  ContentItem, CreateContentRequest,
  AnalyticsData, AnalyticsQuery
} from '@/types'

// ============================================
// 设备管理 API
// ============================================

export const deviceAPI = {
  // ADB设备管理
  async initializeDeviceManager(): Promise<void> {
    return await invoke('initialize_device_manager')
  },

  async scanAdbDevices(): Promise<Device[]> {
    return await invoke('scan_adb_devices')
  },

  async connectAdbDevice(deviceId: string): Promise<void> {
    return await invoke('connect_adb_device', { device_id: deviceId })
  },

  async disconnectAdbDevice(deviceId: string): Promise<void> {
    return await invoke('disconnect_adb_device', { device_id: deviceId })
  },

  async takeDeviceScreenshot(deviceId: string): Promise<Uint8Array> {
    return await invoke('take_device_screenshot', { device_id: deviceId })
  },

  async getDevicePerformance(deviceId: string): Promise<any> {
    return await invoke('get_device_performance', { device_id: deviceId })
  },

  async getAllAdbDevices(): Promise<Device[]> {
    return await invoke('get_all_adb_devices')
  },

  // Legacy API (数据库操作)
  async getDevices(): Promise<Device[]> {
    return await invoke('get_devices')
  },

  async getDevice(id: string): Promise<Device | null> {
    return await invoke('get_device', { id })
  },

  async createDevice(request: CreateDeviceRequest): Promise<string> {
    return await invoke('create_device', { request })
  },

  async updateDeviceStatus(id: string, status: string): Promise<void> {
    return await invoke('update_device_status', { id, status })
  },

  async connectDevice(id: string): Promise<void> {
    return await invoke('connect_device', { id })
  },

  async disconnectDevice(id: string): Promise<void> {
    return await invoke('disconnect_device', { id })
  },

  async deleteDevice(id: string): Promise<void> {
    return await invoke('delete_device', { id })
  },

  async updateHeartbeat(id: string): Promise<void> {
    return await invoke('update_device_heartbeat', { id })
  },

  async getStats(): Promise<any> {
    return await invoke('get_device_stats')
  },

  // ADB设备管理
  async initializeDeviceManager(): Promise<void> {
    return await invoke('initialize_device_manager')
  },

  async scanAdbDevices(): Promise<any[]> {
    return await invoke('scan_adb_devices')
  },

  async connectAdbDevice(deviceId: string): Promise<void> {
    return await invoke('connect_adb_device', { device_id: deviceId })
  },

  async disconnectAdbDevice(deviceId: string): Promise<void> {
    return await invoke('disconnect_adb_device', { device_id: deviceId })
  },

  async takeDeviceScreenshot(deviceId: string): Promise<any> {
    return await invoke('take_device_screenshot', { device_id: deviceId })
  },

  async getDevicePerformance(deviceId: string): Promise<any> {
    return await invoke('get_device_performance', { device_id: deviceId })
  },

  async getAllAdbDevices(): Promise<any[]> {
    return await invoke('get_all_adb_devices')
  }
}

// ============================================
// 账号管理 API  
// ============================================

export const accountAPI = {
  // 获取账号列表
  async getAccounts(): Promise<SocialAccount[]> {
    return await invoke('get_accounts')
  },

  // 根据平台获取账号
  async getAccountsByPlatform(platform: string): Promise<SocialAccount[]> {
    return await invoke('get_accounts_by_platform', { platform })
  },

  // 创建账号
  async createAccount(request: CreateAccountRequest): Promise<string> {
    return await invoke('create_account', { request })
  },

  // 分配账号到设备
  async assignToDevice(accountId: string, deviceId: string): Promise<void> {
    return await invoke('assign_account_to_device', { account_id: accountId, device_id: deviceId })
  },

  // 账号登录
  async login(accountId: string): Promise<void> {
    return await invoke('login_account', { account_id: accountId })
  },

  // 账号登出
  async logout(accountId: string): Promise<void> {
    return await invoke('logout_account', { account_id: accountId })
  },

  // 验证账号
  async verify(accountId: string): Promise<boolean> {
    return await invoke('verify_account', { account_id: accountId })
  },

  // 刷新账号信息
  async refreshInfo(accountId: string): Promise<void> {
    return await invoke('refresh_account_info', { account_id: accountId })
  },

  // 获取账号统计
  async getStats(): Promise<any> {
    return await invoke('get_account_stats')
  }
}

// ============================================
// 任务管理 API
// ============================================

export const taskAPI = {
  // 获取任务列表
  async getTasks(options?: {
    status?: string
    limit?: number
    offset?: number
  }): Promise<Task[]> {
    return await invoke('get_tasks', options)
  },

  // 创建任务
  async createTask(request: CreateTaskRequest): Promise<string> {
    return await invoke('create_task', { request })
  },

  // 启动任务
  async startTask(taskId: string): Promise<void> {
    return await invoke('start_task', { task_id: taskId })
  },

  // 暂停任务
  async pauseTask(taskId: string): Promise<void> {
    return await invoke('pause_task', { task_id: taskId })
  },

  // 完成任务
  async completeTask(taskId: string, result?: any): Promise<void> {
    return await invoke('complete_task', { task_id: taskId, result })
  },

  // 任务失败
  async failTask(taskId: string, errorMessage: string, errorCode?: string): Promise<void> {
    return await invoke('fail_task', { task_id: taskId, error_message: errorMessage, error_code: errorCode })
  },

  // 重试任务
  async retryTask(taskId: string): Promise<void> {
    return await invoke('retry_task', { task_id: taskId })
  },

  // 更新任务进度
  async updateProgress(taskId: string, percentage: number, currentStep?: string): Promise<void> {
    return await invoke('update_task_progress', { task_id: taskId, percentage, current_step: currentStep })
  },

  // 删除任务
  async deleteTask(taskId: string): Promise<void> {
    return await invoke('delete_task', { task_id: taskId })
  },

  // 获取任务日志
  async getTaskLogs(taskId: string, limit?: number): Promise<TaskLog[]> {
    return await invoke('get_task_logs', { task_id: taskId, limit })
  },

  // 添加任务日志
  async addLog(taskId: string, level: string, message: string, details?: string, stepName?: string): Promise<void> {
    return await invoke('add_task_log', { task_id: taskId, level, message, details, step_name: stepName })
  },

  // 获取任务统计
  async getStats(): Promise<any> {
    return await invoke('get_task_stats')
  }
}

// ============================================
// 内容管理 API
// ============================================

export const contentAPI = {
  // 获取内容库
  async getContentLibrary(
    contentTypeFilter?: string,
    platformFilter?: string
  ): Promise<ContentItem[]> {
    return await invoke('get_content_library', { contentTypeFilter, platformFilter })
  },

  // 创建内容
  async createContent(request: CreateContentRequest): Promise<string> {
    return await invoke('create_content', { request })
  },

  // 上传内容文件
  async uploadContentFile(
    filePath: string,
    contentType: string,
    platform: string
  ): Promise<string> {
    return await invoke('upload_content_file', { filePath, contentType, platform })
  }
}

// ============================================
// 统计分析 API
// ============================================

export const analyticsAPI = {
  // 获取分析数据
  async getAnalytics(query: AnalyticsQuery): Promise<AnalyticsData[]> {
    return await invoke('get_analytics', { query })
  },

  // 获取仪表板统计
  async getDashboardStats(): Promise<any> {
    return await invoke('get_dashboard_stats')
  }
}

// ============================================
// 系统配置 API
// ============================================

export const systemAPI = {
  // 获取系统配置
  async getSystemConfig(): Promise<any> {
    return await invoke('get_system_config')
  },

  // 更新系统配置
  async updateSystemConfig(key: string, value: string): Promise<boolean> {
    return await invoke('update_system_config', { configKey: key, configValue: value })
  },

  // 检查应用更新
  async checkAppUpdate(): Promise<any> {
    return await invoke('check_app_update')
  },

  // 导出数据
  async exportData(dataType: string, filePath: string): Promise<boolean> {
    return await invoke('export_data', { dataType, filePath })
  },

  // 导入数据
  async importData(dataType: string, filePath: string): Promise<number> {
    return await invoke('import_data', { dataType, filePath })
  }
}

// ============================================
// API 错误处理包装器
// ============================================

// 通用 API 调用包装器，用于错误处理和重试
export async function apiCall<T>(
  apiFunction: () => Promise<T>,
  retries: number = 3,
  delay: number = 1000
): Promise<T> {
  let lastError: Error

  for (let i = 0; i < retries; i++) {
    try {
      return await apiFunction()
    } catch (error) {
      lastError = error as Error
      console.error(`API call failed (attempt ${i + 1}):`, error)
      
      // 如果不是最后一次重试，等待后重试
      if (i < retries - 1) {
        await new Promise(resolve => setTimeout(resolve, delay * Math.pow(2, i)))
      }
    }
  }

  throw lastError!
}

// ============================================
// 兼容性导出 - 为了向后兼容
// ============================================

// 设备相关
export const getDevices = deviceAPI.getDevices
export const createDevice = deviceAPI.createDevice
export const updateDeviceStatus = deviceAPI.updateDeviceStatus
export const deleteDevice = deviceAPI.deleteDevice

// 账号相关  
export const getAccounts = accountAPI.getAccounts
export const createAccount = accountAPI.createAccount
export const updateAccount = accountAPI.refreshInfo // 使用 refreshInfo 作为更新
export const deleteAccount = async(_accountId: string) => {
  // 暂时空实现，等待后端实现
  console.warn('deleteAccount not implemented yet')
}

// 任务相关
export const getTasks = taskAPI.getTasks
export const createTask = taskAPI.createTask
export const updateTask = taskAPI.updateProgress // 使用 updateProgress 作为更新
export const deleteTask = taskAPI.deleteTask

// 内容相关
export const getContentLibrary = contentAPI.getContentLibrary
export const createContent = contentAPI.createContent

// ============================================
// 批量操作 API
// ============================================

export const batchAPI = {
  // 批量操作设备
  async batchDeviceOperation(
    deviceIds: string[], 
    operation: 'connect' | 'disconnect'
  ): Promise<{ success: string[], failed: string[] }> {
    const results = await Promise.allSettled(
      deviceIds.map(id => 
        operation === 'connect' 
          ? deviceAPI.connectDevice(id)
          : deviceAPI.disconnectDevice(id)
      )
    )

    const success: string[] = []
    const failed: string[] = []

    results.forEach((result, index) => {
      if (result.status === 'fulfilled') {
        success.push(deviceIds[index])
      } else {
        failed.push(deviceIds[index])
      }
    })

    return { success, failed }
  },

  // 批量操作任务
  async batchTaskOperation(
    taskIds: string[],
    operation: 'start' | 'pause'
  ): Promise<{ success: string[], failed: string[] }> {
    const results = await Promise.allSettled(
      taskIds.map(id => 
        operation === 'start'
          ? taskAPI.startTask(id)
          : taskAPI.pauseTask(id)
      )
    )

    const success: string[] = []
    const failed: string[] = []

    results.forEach((result, index) => {
      if (result.status === 'fulfilled') {
        success.push(taskIds[index])
      } else {
        failed.push(taskIds[index])
      }
    })

    return { success, failed }
  }
}